#include"freq.h"

int countFrequency(char * filename,CharFreq * frequencies){

    FILE * fptr = fopen(filename,"r");
    if(NULL == fptr){

        printf("open file %s failed.\n",filename);
        return 0;
    }
    int count = 0;
    while(!feof(fptr)){

        int onechar = fgetc(fptr);
        if(EOF!=onechar){

            count++;
            frequencies[onechar].value = (char)onechar;
            frequencies[onechar].freq++;
        }else{

            break;
        }
    }
    fclose(fptr);
    return count;
}

void printFrequency(CharFreq * freq){

    for(int index = 0;index < NUMLETTER;index++){

        printf("value = %c, freq = %d.\n",freq[index].value,freq[index].freq);
    }
    printf("---------------------------------------.\n");
}

static int compareFreq(const void * p1,const void * p2){

    const CharFreq * ip1 = (const CharFreq*)p1;
    const CharFreq * ip2 = (const CharFreq*)p2;
    const int iv1 = ip1->freq;
    const int iv2 = ip2->freq;

    return (iv1-iv2); 
}

void sortFrequency(CharFreq * freq){

    qsort(freq,NUMLETTER,sizeof(CharFreq),compareFreq);
}
